package cn.zifangsky.jvm.part2.reference;

import java.lang.ref.SoftReference;

/**
 * 软引用
 *
 * @author zifangsky
 * @date 2020/7/11
 * @since 1.0.0
 */
public class SoftRef {
    /**
     * JVM参数：
     * -Xms20M -Xmx20M -Xmn12M -XX:SurvivorRatio=2 -XX:+UseSerialGC -XX:+PrintGCDetails -verbose:gc
     */
    public static void main(String[] args) {
        User u = new User(1, "admin");
        SoftReference<User> userSoftRef = new SoftReference<>(u);
        //去除强引用
        u = null;

        System.out.println(userSoftRef.get());
        System.gc();
        System.out.println("第一次GC后：" + userSoftRef.get());

        System.out.println("********** 第二次GC **********");
        //再申请一个占6M内存的数组，此时内存空间不够触发Full GC，自动清除软引用
        byte[] b = new byte[1024 * 1024 * 6];
        System.gc();
        System.out.println("第二次GC后：" + userSoftRef.get());
    }


    public static class User {
        private int id;
        private String name;
        private byte[] arr;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
            //默认申请一个占4M内存的数组
            this.arr = new byte[1024 * 1024 * 4];
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "[id=" + String.valueOf(id) + ", name=" + name + "]";
        }
    }
}
